package es.unileon.is.finalproyect.temporizer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TimeLabel extends JLabel implements TimeListener{

	public TimeLabel() {
		super("Remainig time:  --:--");
	}

	public TimeLabel(TimeSource ts){
		this();
		setTimeSource(ts);
	}
	
	public void setTimeSource(TimeSource ts){
		ts.addTimeListener(this);
	}
	
	@Override
	public void newTime(TimeEvent evt) {
		final int seconds = evt.getSeconds();
		if(SwingUtilities.isEventDispatchThread()){
			changeTime(seconds);
		} else try {
			SwingUtilities.invokeAndWait(new Runnable(){
				public void run(){
					changeTime(seconds);
				}
			});
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e){
			e.printStackTrace();
		}
	}
	
	private void changeTime(int seconds){
		int minutes = seconds/60;
		int restSeconds = seconds-(minutes*60);
		String minutesString = Integer.toString(minutes);
		if(minutesString.length()<2){
			minutesString = "0" + minutesString;
		}
		String secondsString = Integer.toString(restSeconds);
		if(secondsString.length() < 2){
			secondsString = "0" + secondsString;
		}
		setText("Remaining time:  " + minutesString + ":" + secondsString);
	}
	
	public Dimension getPreferredSize(){
		String text = getText();
		FontMetrics fm = getFontMetrics(getFont());
		int w = fm.stringWidth(text);
		int h = fm.getHeight();
		return new Dimension(w,h);
	}

}
